package com.handu.luna.mall.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import com.handu.luna.core.domain.user.User;
import com.handu.luna.core.domain.user.User.UserStatus;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.patchca.color.ColorFactory;
import org.patchca.filter.predefined.*;
import org.patchca.service.ConfigurableCaptchaService;
import org.patchca.utils.encoder.EncoderHelper;
import org.patchca.word.RandomWordFactory;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.awt.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.mail.Message.RecipientType;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

@SuppressWarnings("restriction")
@Controller
@RequestMapping("/login/*")
public class LoginController extends BaseController {
	/**
	 * 跳转登陆页面
	 */
	@RequestMapping(value = { "index" })
	public MallModelView index() {
		return buildModelView("/login/login");
	}

	/**
	 * 登陆
	 * 
	 * @param name
	 * @param password
	 */
	@RequestMapping(value = "login", method = RequestMethod.POST)
	public @ResponseBody String index(String mobileOrEmail, String password,
			String autoLogin, HttpServletRequest request,
			HttpServletResponse response) {
    	if(verifyLogin(mobileOrEmail, password, autoLogin, request, response)){
    		List<User> user = context.getUserRepository().findByMobile(mobileOrEmail);
    		if(!user.isEmpty()){
    			String token = AES(user.get(0).getId()
    					+ user.get(0).getPasswordSalt(), user.get(0).getId()
    					+ user.get(0).getPasswordSalt());
    			String salt = user.get(0).getPasswordSalt();
    			List<User> isUser = context.getUserRepository().findByMobileAndPassword(
    					mobileOrEmail,
    					SHA256Encrypt(password + user.get(0).getId() + salt
    							+ token));
    			if(!isUser.isEmpty() && isUser.get(0).getStatus().name()=="LOCKED"){
    				return "locked";
    			}
    		}
    		
    		Cookie userName = new Cookie("luna_session_name",mobileOrEmail);
    		userName.setPath("/");
    		userName.setMaxAge(60 * 60 * 24 * 14);
			response.addCookie(userName);
    		return "true";
    	}else{
    		return "false";
    	}
	}
	
	/**
	 * 跳转登陆
	 * 
	 * @param name
	 * @param password
	 */
	@RequestMapping(value = "returnLogin", method = RequestMethod.POST)
	public MallModelView returnLogin(String mobileOrEmail, String password,
			String autoLogin,HttpServletResponse response, HttpServletRequest request
			) {
    	if(verifyLogin(mobileOrEmail, password, autoLogin, request, response)){
    		Pattern checkMobile = Pattern
    				.compile("1[3|5|7|8|][0-9]{9}");

    		Pattern checkEmail = Pattern
    				.compile("^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\\.([a-zA-Z0-9_-])+)+$");
    		Matcher m1 = checkMobile.matcher(mobileOrEmail);
    		Matcher m2 = checkEmail.matcher(mobileOrEmail);
    		List<User> user = null;
    		if (m1.matches()){
    			user = context.getUserRepository().findByMobile(mobileOrEmail);
    		}else if(m2.matches()){
    			user = context.getUserRepository().findByEmail(mobileOrEmail);
    		}
    		Cookie userName = new Cookie("luna_session_name",mobileOrEmail);
    		userName.setPath("/");
    		userName.setMaxAge(60 * 60 * 24 * 14);
			response.addCookie(userName);
    		return buildModelView("redirect:/").add("email", user.get(0).getName());
    	}else{
    		return buildModelView("redirect:/");
    	}
    	
	}
	
	
	/**
	 * 判断用户登录是否正确
	 * 
	 * @param email
	 * @throws Exception
	 */

	private boolean verifyLogin(String mobileOrEmail, String password,
			String autoLogin, HttpServletRequest request,
			HttpServletResponse response) {
		List<User> isUser = new ArrayList<User>();
		List<User> user = new ArrayList<User>();

		Pattern checkMobile = Pattern
				.compile("1[3|5|7|8|][0-9]{9}");

		Pattern checkEmail = Pattern
				.compile("^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\\.([a-zA-Z0-9_-])+)+$");
		Matcher m1 = checkMobile.matcher(mobileOrEmail);
		Matcher m2 = checkEmail.matcher(mobileOrEmail);
		
		if (m1.matches() && !context.getUserRepository().findByMobile(mobileOrEmail).isEmpty()) {
				user = context.getUserRepository().findByMobile(mobileOrEmail);
				String token = AES(user.get(0).getId()
						+ user.get(0).getPasswordSalt(), user.get(0).getId()
						+ user.get(0).getPasswordSalt());
				String salt = user.get(0).getPasswordSalt();
				isUser = context.getUserRepository().findByMobileAndPassword(
						mobileOrEmail,
						SHA256Encrypt(password + user.get(0).getId() + salt
								+ token));
				if (CollectionUtils.isEmpty(isUser)) {
					
					return false;
				} else {
					if(user.get(0).getUserRank()==null){
						user.get(0).initUserRank(user.get(0));
					}
					user.get(0).setInvalidPasswordTryCount(0);;
					user.get(0).setLastInvalidPasswordTime(null);
					user.get(0).setAtuLogin(autoLogin);
					this.getSession().setUser(user.get(0));
					return true;
				}
			

		} else if (m2.matches() && !context.getUserRepository().findByEmail(mobileOrEmail).isEmpty()) {
			 	user = context.getUserRepository().findByEmail(mobileOrEmail);
				String token = AES(user.get(0).getId()
						+ user.get(0).getPasswordSalt(), user.get(0).getId()
						+ user.get(0).getPasswordSalt());
				String salt = user.get(0).getPasswordSalt();
				System.err.println(SHA256Encrypt(password + user.get(0).getId() + salt
						+ token));
				isUser = context.getUserRepository().findByEmailAndPassword(
						mobileOrEmail,
						SHA256Encrypt(password + user.get(0).getId() + salt
								+ token));
				if (CollectionUtils.isEmpty(isUser)) {
					
					return false;
				} else {
					if(user.get(0).getUserRank()==null){
						if(user.get(0).getUserRank()==null){
							user.get(0).initUserRank(user.get(0));
						}
					}
					user.get(0).setInvalidPasswordTryCount(0);;
					user.get(0).setLastInvalidPasswordTime(null);
					user.get(0).setAtuLogin(autoLogin);
					this.getSession().setUser(user.get(0));
					return true;
				}
			

		}
		return false;
	}


	/**
	 * 跳转到注册页面
	 * 
	 * @param name
	 * @param password
	 */
	@RequestMapping(value = "register", method = RequestMethod.GET)
	public MallModelView list() {
		return buildModelView("/login/register");
	}

	/**
	 * 注册
	 * 
	 * @param name
	 * @param password
	 * @throws Exception
	 */
	@RequestMapping(value = "register", method = RequestMethod.POST)
	public MallModelView save(String email, String password) throws Exception {
		String salt = createRandom();
		// String password = user.getPassword();
		User user = null;
		Pattern checkMobile = Pattern
				.compile("1[3|5|7|8|][0-9]{9}");

		Pattern checkEmail = Pattern
				.compile("^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\\.([a-zA-Z0-9_-])+)+$");
		Matcher m1 = checkMobile.matcher(email.trim());
		Matcher m2 = checkEmail.matcher(email.trim());
		
		if (m1.matches()) {
			user = new User();
			user.setMobile(email.trim());
			User userPassword = context.getUserRepository().save(user);
			String token = AES(userPassword.getId() + salt,
					userPassword.getId() + salt);
			user.setPasswordSalt(salt);
			userPassword.setPassword(SHA256Encrypt(password + user.getId()
					+ salt + token));
			userPassword.setStatus(UserStatus.NORMAL);
			userPassword.setIsMobileCheck("是");
			userPassword.setName(email);
			context.getUserRepository().save(userPassword);
		} else if (m2.matches()) {
			user = new User();
			user.setEmail(email.trim());
			User userPassword = context.getUserRepository().save(user);
			String token = AES(userPassword.getId() + salt,
					userPassword.getId() + salt);
			user.setPasswordSalt(salt);
			userPassword.setPassword(SHA256Encrypt(password + user.getId()
					+ salt + token));
			userPassword.setStatus(UserStatus.NORMAL);
			userPassword.setIsEmailCheck("是");
			userPassword.setName(email);
			context.getUserRepository().save(userPassword);
		}

		// context.getUserRepository().save(user);
		return buildModelView("/login/register_success").add("username", user.getName()).add("email", email).add("password", password);
	}

	/**
	 * 跳转重置密码页面
	 */
	@RequestMapping(value = { "passReset" })
	public MallModelView add() {
		return buildModelView("/login/pass_return");
	}

	public static Session getMailSession() {
		Properties props = new Properties();
		props.setProperty("mail.transport.protocol", "smtp");
		props.setProperty("mail.smtp.host", "smtp.qq.com");
		props.setProperty("mail.smtp.port", "25");
		props.setProperty("mail.smtp.auth", "true");
		Session session = Session.getInstance(props, new Authenticator() {

			@Override
			protected PasswordAuthentication getPasswordAuthentication() {

				return new PasswordAuthentication("admin@hstyle.com",
						"hdys2013aabb");
			}

		});
		return session;
	}
	
	 @RequestMapping(value = "resetPassword", method = RequestMethod.POST)
	  public MallModelView resetPassword(String email, String password) { // 发送重新设置密码的链接
		 Pattern checkMobile = Pattern
					.compile("1[3|5|7|8|][0-9]{9}");

			Pattern checkEmail = Pattern
					.compile("^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\\.([a-zA-Z0-9_-])+)+$");
			Matcher m1 = checkMobile.matcher(email);
			Matcher m2 = checkEmail.matcher(email);
			List<User> userList = new ArrayList<User>();
			if(m1.matches()){
				userList = context.getUserRepository().findByMobile(email);
				
			}else if(m2.matches()){
				userList = context.getUserRepository().findByEmail(email);
			}
	  
	  
	  User users =  userList.get(0);
	  String token = AES(users.getId() + users.getPasswordSalt(),
			  users.getId() + users.getPasswordSalt());
	  users.setPassword(SHA256Encrypt(password + users.getId()
				+ users.getPasswordSalt() + token));
	 
	  context.getUserRepository().save(users); 
	  
	  return buildModelView("/login/pass_reset_success").add("email", email).add("password", password); 
	  }

	/**
	 * 重置密码
	 * 
	 */
	@RequestMapping(value = "registerReset", method = RequestMethod.POST)
	public MallModelView registerReset(HttpServletRequest request, String email) {
		Pattern checkMobile = Pattern
				.compile("1[3|5|7|8|][0-9]{9}");

		Pattern checkEmail = Pattern
				.compile("^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\\.([a-zA-Z0-9_-])+)+$");
		Matcher m1 = checkMobile.matcher(email);
		Matcher m2 = checkEmail.matcher(email);
		if(m1.matches()){
			List<User> users = context.getUserRepository().findByMobile(email);
			System.err.println(users.get(0).getMobile());
			return buildModelView("/login/pass_reset").add("mobile", users.get(0).getMobile());
		}
		
		if(m2.matches()){
			List<User> users = context.getUserRepository().findByEmail(email);
			String secretKey = UUID.randomUUID().toString(); // 密钥
			Timestamp outDate = new Timestamp(
					System.currentTimeMillis() + 30 * 60 * 1000);// 30分钟后过期
			long date = outDate.getTime() / 1000 * 1000; // 忽略毫秒数
			users.get(0).setValidataCode(secretKey);
			users.get(0).setRegisterDate(outDate);
			context.getUserRepository().save(users.get(0));// 保存到数据库
			String key = users.get(0).getEmail() + "$" + date + "$" + secretKey;
			String digitalSignature = Base64.encode(key.getBytes());// MD5.MD5Encode(key);
																	// // 数字签名

			String resetPassHref = EMAIL_CONTEXT_PATH+"/login/resetPasswordUI?sid="
					+ digitalSignature + "&email=" + users.get(0).getEmail();
			Session session = getMailSession();
			MimeMessage message = new MimeMessage(session);
			try {
				message.setSubject("找回您的帐户与密码");
				message.setSentDate(new Date());
				message.setFrom(new InternetAddress("admin@hstyle.com"));
				message.setRecipient(RecipientType.TO, new InternetAddress(users
						.get(0).getEmail()));

				message.setContent("请勿回复本邮件.点击下面的链接,重设密码<br/><a href="
						+ resetPassHref + " target='_BLANK'>点击我重新设置密码</a>"
						+ "<br/>tips:本邮件超过30分钟,链接将会失效，需要重新申请'找回密码'" + key + "\t"
						+ digitalSignature, "text/html;charset=utf-8");

				// 发送邮件
				Transport.send(message);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return buildModelView("/login/pass_return").add("email", users.get(0).getEmail());
		}
		return null;
		
	}

	@RequestMapping(value = "resetPasswordUI", method = RequestMethod.GET)
	public MallModelView resetPasswordUI(String sid, String email) {
		List<User> users = context.getUserRepository().findByEmail(email);

		Timestamp outDate = users.get(0).getRegisterDate();

		String key = users.get(0).getEmail() + "$" + outDate.getTime() / 1000
				* 1000 + "$" + users.get(0).getValidataCode(); // 数字签名
		String digitalSignature = Base64.encode(key.getBytes());
		System.out.println(key + "\t" + digitalSignature);
		if (digitalSignature.equals(sid)) {
			return buildModelView("/login/pass_reset")
					.add("email", users.get(0).getEmail());
		}

		return buildModelView("/login/pass_reset").add("email", users.get(0).getEmail());
	}

	/**
	 * 生成六位随机数
	 * 
	 * @param email
	 */
	private String createRandom() {
		int[] array = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
		Random rand = new Random();
		for (int i = 10; i > 1; i--) {
			int index = rand.nextInt(i);
			int tmp = array[index];
			array[index] = array[i - 1];
			array[i - 1] = tmp;
		}
		int result = 0;
		for (int i = 0; i < 6; i++)
			result = result * 10 + array[i];
		return String.valueOf(result);
		// System.err.println(result);
	}

	/**
	 * 使用SHA-256 算法 加密，默认模式 AES/ECB
	 */

	public static String SHA256Encrypt(String orignal) {
		String ALGORITHM = "SHA-256";
		MessageDigest md = null;
		try {
			md = MessageDigest.getInstance(ALGORITHM);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		if (null != md) {
			byte[] origBytes = orignal.getBytes();
			md.update(origBytes);
			byte[] digestRes = md.digest();
			String digestStr = getDigestStr(digestRes);
			System.err.println(digestStr);
			return digestStr;
		}

		return null;
	}

	private static String getDigestStr(byte[] origBytes) {
		String tempStr = null;
		StringBuilder stb = new StringBuilder();
		for (int i = 0; i < origBytes.length; i++) {
			tempStr = Integer.toHexString(origBytes[i] & 0xff);
			if (tempStr.length() == 1) {
				stb.append("0");
			}
			stb.append(tempStr);

		}
		return stb.toString();
	}

	/**
	 * 使用AES 算法 加密，默认模式 AES/ECB
	 */
	public static String AES(String content, String password) {
		try {
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
			kgen.init(128, new SecureRandom(password.getBytes()));
			SecretKey secretKey = kgen.generateKey();
			byte[] enCodeFormat = secretKey.getEncoded();
			SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
			Cipher cipher = Cipher.getInstance("AES");// 创建密码器
			byte[] byteContent = content.getBytes("utf-8");
			cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
			byte[] result = cipher.doFinal(byteContent);
			return parseByte2HexStr(result); // 加密
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String parseByte2HexStr(byte buf[]) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < buf.length; i++) {
			String hex = Integer.toHexString(buf[i] & 0xFF);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}
			sb.append(hex.toUpperCase());
		}
		return sb.toString();
	}

	

	/**
	 * 检查 手机/邮箱 是否存在
	 * 
	 * @param email
	 */
	@RequestMapping(value = "verifyEamilOrMobile", method = RequestMethod.POST)
	public @ResponseBody boolean list(String email) {
		int numEmail = context.getUserRepository().findByEmail(email).size();
		int numMobile = context.getUserRepository().findByMobile(email).size();

		if (numEmail != 0 || numMobile != 0) {
			return false;
		} else {
			return true;
		}
	}
	
	/**
	 * 检查 手机/邮箱 是否存在
	 * 
	 * @param email
	 */
	@RequestMapping(value = "verifyMobileOrEamil", method = RequestMethod.POST)
	public @ResponseBody boolean verifyMobileOrEamil(String email) {
		int numEmail = context.getUserRepository().findByEmail(email).size();
		int numMobile = context.getUserRepository().findByMobile(email).size();

		if (numEmail != 0 || numMobile != 0) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 验证码填写是否正确
	 * 
	 * @param email
	 */
	@RequestMapping(value = "verifyAuthcode", method = RequestMethod.POST)
	public @ResponseBody boolean index(HttpServletRequest request,
			String authcode) {
		HttpSession session = request.getSession();
		String token = (String) session.getAttribute("captchaToken");
		if (authcode.equalsIgnoreCase(token)) {
			return true;
		} else {
			return false;
		}
	}
	
	/**
	 * 验证码填写是否正确
	 * 
	 * @param email
	 */
	@RequestMapping(value = "verifyAuthcodeRest", method = RequestMethod.POST)
	public @ResponseBody boolean verifyAuthcodeRest(HttpServletRequest request,
			String authcode) {
		HttpSession session = request.getSession();
		String token = (String) session.getAttribute("captchaTokenRest");
		if (authcode.equalsIgnoreCase(token)) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 手机验证码填写是否正确
	 * 
	 * @param email
	 */
	@RequestMapping(value = "verifyTelphonecode", method = RequestMethod.POST)
	public @ResponseBody boolean verifyTelphonecode(HttpServletRequest request,
			String authcode) {
		HttpSession session = request.getSession();
		String token = (String) session.getAttribute("telphoneToken");
		if (authcode.equalsIgnoreCase(token)) {
			return true;
		} else {
			return false;
		}
	}
	
	/**
	 * 手机验证码填写是否正确
	 * 
	 * @param email
	 */
	@RequestMapping(value = "verifyTelphonecodeRest", method = RequestMethod.POST)
	public @ResponseBody boolean verifyTelphonecodeRest(HttpServletRequest request,
			String authcode) {
		HttpSession session = request.getSession();
		String token = (String) session.getAttribute("telphoneTokenRest");
		if (authcode.equalsIgnoreCase(token)) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 验证码生成
	 * 
	 * @param email
	 */
	private static ConfigurableCaptchaService cs = new ConfigurableCaptchaService();
	private static Random random = new Random();
	static {
		cs.setColorFactory(new ColorFactory() {
			@Override
			public Color getColor(int x) {
				int[] c = new int[3];
				int i = random.nextInt(c.length);
				for (int fi = 0; fi < c.length; fi++) {
					if (fi == i) {
						c[fi] = random.nextInt(71);
					} else {
						c[fi] = random.nextInt(256);
					}
				}
				return new Color(c[0], c[1], c[2]);
			}
		});
		RandomWordFactory wf = new RandomWordFactory();
		wf.setCharacters("23456789abcdefghigkmnpqrstuvwxyzABCDEFGHIGKLMNPQRSTUVWXYZ");
		wf.setMaxLength(4);
		wf.setMinLength(4);
		cs.setWordFactory(wf);
	}

	@RequestMapping(value = "/pcrimg")
	public void crimg(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		switch (random.nextInt(5)) {
		case 0:
			cs.setFilterFactory(new CurvesRippleFilterFactory(cs
					.getColorFactory()));
			break;
		case 1:
			cs.setFilterFactory(new MarbleRippleFilterFactory());
			break;
		case 2:
			cs.setFilterFactory(new DoubleRippleFilterFactory());
			break;
		case 3:
			cs.setFilterFactory(new WobbleRippleFilterFactory());
			break;
		case 4:
			cs.setFilterFactory(new DiffuseRippleFilterFactory());
			break;
		}
		HttpSession session = request.getSession(false);
		if (session == null) {
			session = request.getSession();
		}
		setResponseHeaders(response);
		String token = EncoderHelper.getChallangeAndWriteImage(cs, "png",
				response.getOutputStream());
		session.setAttribute("captchaToken", token);
		// System.out.println("当前的SessionID=" + session.getId() + "，验证码=" +
		// token);
	}
	
	@RequestMapping(value = "/pcrimgRest")
	public void pcrimgRest(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		switch (random.nextInt(5)) {
		case 0:
			cs.setFilterFactory(new CurvesRippleFilterFactory(cs
					.getColorFactory()));
			break;
		case 1:
			cs.setFilterFactory(new MarbleRippleFilterFactory());
			break;
		case 2:
			cs.setFilterFactory(new DoubleRippleFilterFactory());
			break;
		case 3:
			cs.setFilterFactory(new WobbleRippleFilterFactory());
			break;
		case 4:
			cs.setFilterFactory(new DiffuseRippleFilterFactory());
			break;
		}
		HttpSession session = request.getSession(false);
		if (session == null) {
			session = request.getSession();
		}
		setResponseHeaders(response);
		String tokenRest = EncoderHelper.getChallangeAndWriteImage(cs, "png",
				response.getOutputStream());
		session.setAttribute("captchaTokenRest", tokenRest);
		// System.out.println("当前的SessionID=" + session.getId() + "，验证码=" +
		// token);
	}

	protected void setResponseHeaders(HttpServletResponse response) {
		response.setContentType("image/png");
		response.setHeader("Cache-Control", "no-cache, no-store");
		response.setHeader("Pragma", "no-cache");
		long time = System.currentTimeMillis();
		response.setDateHeader("Last-Modified", time);
		response.setDateHeader("Date", time);
		response.setDateHeader("Expires", time);
	}

	/**
	 * 短信验证码生成
	 * 
	 * @param mobile
	 * @throws Exception
	 */

	@RequestMapping(value = "/mobilePcrimg")
	public void index(HttpServletRequest request, HttpServletResponse response,
			String telcode) throws Exception {
		HttpClient client = new HttpClient();
		PostMethod post = new PostMethod(
				"http://113.59.109.38:8050/SendSms2014.aspx");
		post.addRequestHeader("Content-Type",
				"application/x-www-form-urlencoded;charset=gbk");// 在头文件中设置转码
		String salt = createRandom();
		String telphoneToken ="禀主子,您的验证码为:"+salt+",切勿将验证码泄露给他人.恭请小主下载手机客户端,定制你的专属韩都http://url.cn/LwZ4L2";
		NameValuePair[] data = {
				new NameValuePair("spid", "101410"),
				new NameValuePair("pwd", "HANDUSHM"),
				new NameValuePair("mobiles", telcode),
				new NameValuePair("sms",getURLDecoder(getBASE64(telphoneToken))) };
		post.setRequestBody(data);

		try {
			client.executeMethod(post);
		} catch (HttpException e) {
			System.err.println(e.getMessage());
			e.printStackTrace();
		} catch (IOException e) {
			System.err.println(e.getMessage());
			e.printStackTrace();
		}

		try {
			System.err.println(post.getResponseBodyAsString().toString());
		} catch (IOException e) {
			e.printStackTrace();
		}

		HttpSession session = request.getSession(false);
		if (session == null) {
			session = request.getSession();
		}
		setResponseHeaders(response);
		session.setAttribute("telphoneToken", salt);
		// System.out.println("当前的SessionID=" + session.getId() + "，验证码=" +
		// token);
	}
	
	/**
	 * 短信验证码生成
	 * 
	 * @param mobile
	 * @throws Exception
	 */

	@RequestMapping(value = "/mobilePcrimgRest")
	public void mobilePcrimgRest(HttpServletRequest request, HttpServletResponse response,
			String telcode) throws Exception {
		HttpClient client = new HttpClient();
		PostMethod post = new PostMethod(
				"http://113.59.109.38:8050/SendSms2014.aspx");
		post.addRequestHeader("Content-Type",
				"application/x-www-form-urlencoded;charset=gbk");// 在头文件中设置转码
		String salt = createRandom();
		String telphoneTokenRest ="禀主子,您的验证码为:"+ salt +",切勿将验证码泄露给他人.如非小主操作,建议及时修改账号密码.下载客户端,定制你专属韩都—http://url.cn/LwZ4L2";
		NameValuePair[] data = {
				new NameValuePair("spid", "101410"),
				new NameValuePair("pwd", "HANDUSHM"),
				new NameValuePair("mobiles", telcode),
				new NameValuePair("sms", getURLDecoder(getBASE64(telphoneTokenRest)))  };
		post.setRequestBody(data);

		try {
			client.executeMethod(post);
		} catch (HttpException e) {
			System.err.println(e.getMessage());
			e.printStackTrace();
		} catch (IOException e) {
			System.err.println(e.getMessage());
			e.printStackTrace();
		}

		try {
			System.err.println(post.getResponseBodyAsString().toString());
		} catch (IOException e) {
			e.printStackTrace();
		}

		HttpSession session = request.getSession(false);
		if (session == null) {
			session = request.getSession();
		}
		setResponseHeaders(response);
		session.setAttribute("telphoneTokenRest", salt);

	}

	public static String getBASE64(String BASE64) throws UnsupportedEncodingException {
    	
        return (new sun.misc.BASE64Encoder()).encode(BASE64.getBytes("gbk"));

    }


    public static String getURLDecoder(String URLDecoder) throws UnsupportedEncodingException{
    	return  java.net.URLDecoder.decode(URLDecoder,"gbk"); 
    }
}
